﻿using System;
using System.Collections.Generic;
using System.Text;

namespace YhmOA.Common
{
    #region 数据转换类
    /// <summary>
    /// 数据转换类
    /// </summary>
    [Serializable]
    internal class DataConvert
    {
        #region 要转换的数据
        /// <summary>
        /// 要转换的数据
        /// </summary>
        private object data;
        /// <summary>
        /// 要转换的数据
        /// </summary>
        public object Data
        {
            get { return data; }
            set { data = value; }
        }
        #endregion

        #region 要转换成的类型
        /// <summary>
        /// 要转换成的类型
        /// </summary>
        private ResponseType responseType;
        /// <summary>
        /// 要转换成的类型
        /// </summary>
        public ResponseType ResponseType
        {
            get { return responseType; }
            set { responseType = value; }
        }
        #endregion

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="data">要转换的数据</param>
        /// <param name="responseType">要转换成的类型</param>
        public DataConvert(object data, ResponseType responseType)
        {
            this.data = data;
            this.responseType = responseType;
        }
        #endregion

        #region 将指定的值转换成josn数据
        /// <summary>
        /// 将指定的值转换成josn数据
        /// </summary>
        /// <param name="value">要转换的值</param>
        /// <returns></returns>
        private string ToJson(string value)
        {
            return "{\"string\":\"" + value.Replace("\"", "\\\"").Replace("\r\n", "\\r\\n") + "\"}";
        }
        #endregion

        #region 重写ToString()方法
        /// <summary>
        /// 重写ToString()方法
        /// </summary>
        /// <returns>格式化后的字符串</returns>
        public override string ToString()
        {
            string result = "";
            if (this.data != null)
            {
                switch (this.data.GetType().Name.ToLower())
                { 
                    case "string":
                        if (this.responseType == ResponseType.json)
                        {
                            result = this.ToJson(this.data.ToString());
                        }
                        else
                        {
                            result = this.data.ToString();
                        }
                        break;
                }
            }
            return result;
        }
        #endregion
    }
    #endregion
}
